package com.semidata.trp.decision.bid;

import java.lang.reflect.Method;
import java.util.Map;

import com.semidata.rtd.core.service.ServiceManager;
import com.semidata.rtd.engine.job.Job;
import com.semidata.rtd.engine.job.SyncTask;
import com.semidata.trp.algorithm.request.StrategyContext;
import com.semidata.trp.decision.filter.FilterResult;
import com.semidata.trp.decision.job.DecisionJob;
import com.semidata.trp.decision.job.DecisionJobContext;

public class DynamicBidTask extends SyncTask{
	private int index;
	private FilterResult result;
	public DynamicBidTask(Job job, int index, FilterResult result, long timeout) {
		super(job, timeout);
		this.index = index;
		this.result = result;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run() throws Exception {
		// TODO Auto-generated method stub
		try {
		DecisionJob job = ((DecisionJob) getJob());
		DecisionJobContext context = job.getJobContext();
		StrategyContext strategyContext = new StrategyContext(result.getStrategy(),context);
		Map<Integer,Class<?>> algos = ServiceManager.getService(CompileService.class).getAlgos();
		Class<?> algoClass = algos.get(result.getStrategy().getAlgoId());
		Method calculateMethod = algoClass.getMethod("calculate", StrategyContext.class);
		Double result = (Double)calculateMethod.invoke(null, strategyContext);
		
		if (result == null || result <= 0.0 || result < this.result.getStrategy().getResource().getFloor()) {
			throw new Exception("algorithm bid fail value : " + result);
		}
		this.result.setPrice(result);
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	public int getIndex() {
		return this.index;
	}

}
